package edu.njust.httpmanager.controller;

import edu.njust.httpmanager.annotation.AuthCheck;
import edu.njust.httpmanager.common.Result;
import edu.njust.httpmanager.constance.ResponseCode;
import edu.njust.httpmanager.constance.UserAuth;
import edu.njust.httpmanager.entity.Catalog;
import edu.njust.httpmanager.entity.dto.CatalogDto;
import edu.njust.httpmanager.service.ICatalogService;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/catalog")
public class CatalogController {

    @Resource
    private ICatalogService catalogService;

    @AuthCheck(UserAuth.EDITOR)
    @PostMapping("/{programId}")
    public Result save(@PathVariable Long programId, @RequestBody Catalog catalog) {

        if (StringUtils.isBlank(catalog.getName())) {
            return Result.error("目录名称不能为空");
        }

        catalog.setProgramId(programId);

        catalogService.save(catalog);

        return Result.success();
    }

    @GetMapping("/{programId}")
    public Result<List<CatalogDto>> getProgramApis(@PathVariable Long programId) {

        // 返回的结果
        List<CatalogDto> catalogs;

        catalogs = catalogService.getAllByProgramId(programId);

        return Result.success(catalogs);
    }

    @AuthCheck(UserAuth.EDITOR)
    @DeleteMapping("/{programId}")
    public Result deleteCatalogByCatalogId(@PathVariable Long programId, Long catalogId) {

        catalogService.deleteCatalog(catalogId);

        return Result.success();
    }

    // 用于修改目录名称
    @AuthCheck(UserAuth.EDITOR)
    @PutMapping("/{programId}")
    public Result update(@PathVariable Long programId, @RequestBody Catalog catalog) {
        // 姓名不能修改为空
        if (catalog.getName() == null) {
            return Result.error(ResponseCode.PARAMS_ERROR);
        }
        catalogService.updateById(catalog);

        return Result.success("更新成功");
    }
}
